/**
 * 
 * @authors Candy
 * @date    2016-07-12 17:34:05
 * @version 1.0.0
 */

var typeID = $.getUrlVar("id");
var typeName = decodeURIComponent($.getUrlVar("name"));
var forword = encodeURIComponent(window.location.href);
var backUrl = $.getUrlVar("back");
//alert(typeID);
var vm = new Vue({
    el: "#app",
    data: {
        screenSide: false,
        time: true, //控制时间tab显示隐藏
        data: [], //列表
        classify: [], //分类
        classify1: [], //筛选
        classify2: [],
        typeID: typeID,
        typeName: typeName,
        tabs: 0,
        noList: false, //处理vm没数据的情况下显示“暂无数据”
        reqOut: false, //判断请求数据是否已完
        newList: {
            isLoading: true,
            pageSize: 21,
            pageIndex: 1
        },
        layout: false, //控制显示方式
        tagTypes: '',

        inputText: '',
        showModal: false,
        shareObj: {
            dataID: '',
            shareTit: '',
            sharePic: ''
        }
    },
    created: function() {
        var dtd = $.Deferred();
        var _self = this;
        //查看上次是否有显示状态的记录先
        var backoperation = $.getCookie('backoperation');
        if (backoperation && typeof(backoperation) === 'string' && backoperation.length > 0) {
            $.setCookie('backoperation', "");
            //查看上次所保存的layout
            var _layout = $.getCookie('layout');
            if (_layout && _layout.length > 0) {
                _self.layout = _layout == "true" ? true : false;
                //只有效一次
                $.setCookie('layout', "");
            }
        }

        /*$.ajax({ 
			url: "/json/look_getListByTypeID.js",
			dataType:"json"
		}).then(function(data){
			_self.time = data.data;
		},function(){
			alert('请求错误');
		});*/
    },
    compiled: function() {
        var _self = this;
        this.loadPhoto();

        $(document).scroll(function() {
            var docHeight = $(document).height(),
                winHeight = $(window).height();
            if ((docHeight > winHeight)&&($(document).scrollTop() >= docHeight - winHeight)) {
                if (!_self.reqOut) {
                    _self.reqOut = true;
                    var str = '<img class="loading-img" src="images/loading.gif"></img>';
                    myLoad.pullLoad('quesCont', str);
                    //$('.quesCont .loadMore').show(); //显示加载效果
                    _self.loadlist(_self.tabs);

                }
            }
        });

        $(document).on('change.inputText', '.fillInput', function() {
            _self.inputText = $(this).val();
        });

        //查看上次是否有Tab记录的先
        var backoperation = $.getCookie('backoperation');
        if (backoperation && typeof(backoperation) === 'string' && backoperation.length > 0) {
            $.setCookie('backoperation', "");
            //查看上次所保存的tab
            var _tabs = $.getCookie('meetingtabs');
            if (_tabs) {
                //前三项有数据过滤的
                _self.tabs = parseInt(_tabs) > 4 ? 0 : parseInt(_tabs);
            }
        }

        _self.slides(_self.tabs);

        //_self.loadlist(_self.tabs);
    },
    ready: function() {
        var _self = this;
        _self.loadPhoto();
        if (history.pushState) {
            window.addEventListener("popstate", function() {
                var query = location.href.split("?")[1];
                //alert(query);
                var hashUrl = query.split("&");
                for (var i = 0; i < hashUrl.length; i++) {
                    if (!(hashUrl[i].indexOf('id') === -1)) {
                        _self.typeID = hashUrl[i].split("=")[1];
                    }
                    if (!(hashUrl[i].indexOf('name') === -1)) {
                        _self.typeName = hashUrl[i].split("=")[1];
                    }
                }
                _self.newList = {
                    isLoading: true,
                    pageSize: PAGESIZE,
                    pageIndex: 1
                };
                _self.loadlist(_self.tabs);
            });
        }
    },
    methods: {
        loadlist: function(tabs) {

            var _self = this;
            var vModal, target; //用来储存不同的tab页面对应的对象
            switch (tabs) { //根据tab的切换来设置sortType的值
                case 0:
                    _self.time = true;
                    var url = 'look_getListByTypeID';
                    var data = {
                        pageSize: _self.newList.pageSize,
                        pageIndex: _self.newList.pageIndex,
                        sortType: '1',
                        typeIDs: _self.typeID
                    }

                    vModal = _self.newList;
                    target = _self.data;
                    break;
                case 1:
                    _self.time = true;
                    var url = 'look_getListByTypeID';
                    var data = {
                        pageSize: _self.newList.pageSize,
                        pageIndex: _self.newList.pageIndex,
                        sortType: '2',
                        typeIDs: _self.typeID
                    };

                    vModal = _self.newList;
                    target = _self.data;
                    break;
                case 2:
                    _self.time = false;
                    var url = 'look_getListByTypeID';
                    var data = {
                        pageSize: _self.newList.pageSize,
                        pageIndex: _self.newList.pageIndex,
                        sortType: '3',
                        typeIDs: _self.typeID
                    };

                    vModal = _self.newList;
                    target = _self.data;
                    break;
                case 3:
                    _self.time = false;
                    var url = 'look_getListByTypeID';
                    var data = {
                        pageSize: _self.newList.pageSize,
                        pageIndex: _self.newList.pageIndex,
                        sortType: '4',
                        typeIDs: _self.typeID
                    };

                    vModal = _self.newList;
                    target = _self.data;
                    break;
                case 4:
                    _self.time = false;
                    var url = 'look_getListByTypeID';
                    var data = {
                        pageSize: _self.newList.pageSize,
                        pageIndex: _self.newList.pageIndex,
                        sortType: '5',
                        typeIDs: _self.typeID
                    };

                    vModal = _self.newList;
                    target = _self.data;
                    break;
                default:

                    break;
            }

            if (!vModal.isLoading) return;
            data = Common.jsonEncode(data);

            if (_self.tagTypes.length > 0) { //如果有tagTypes则拓展data
                var data = $.extend(data, { TagIDs: _self.tagTypes });
            }



            Common.ajaxCall({ url: url, datatype: 'json', type: 'post', data: data }, function(data) {
                if (data.error_code == 0 && data.data.length > 0) {

                    if (vModal.pageIndex == 1) {
                        target.length = 0;
                    }
                    for (var i = 0; i < data.data.length; i++) {
                        target.push(data.data[i]);
                    }
                    _self.reqOut = false;

                    //实际数据与请求的数据量比较
                    if (data.data.length >= vModal.pageSize) {
                        myLoad.pullHide(); //加载后，把效果去掉
                    } else {
                        _self.reqOut = true;
                        myLoad.noDate(); //暂无数据
                        vModal.isLoading = false;
                    }

                } else {
                    if (!(target.length > 0)) { _self.noList = true; } //处理整个vm没有数据的情况，显示“暂无数据”
                    _self.reqOut = true;
                    myLoad.noDate(); //暂无数据
                    vModal.isLoading = false;
                }

                vModal.pageIndex++;
            });

        },
        screen: function() {
            var _self = this;
            _self.screenSide = true;

            // 分类
            var data = {
                parentID: _self.typeID
            };
            Common.ajaxCall({ url: "look_getTypeList", datatype: 'json', type: 'get', data: data }, function(data) {
                if (data.error_code == 0) {
                    _self.classify = data.data;
                } else {
                    alert(data.msg);
                }
            });

            // 获取系统标签
            var defaults1 = {
                tagType: 1,
                type: _self.typeID
            };
            var data1 = $.extend(defaults1, {});
            Common.ajaxCall({ url: "look_getTagList", datatype: 'json', type: 'post', data: data1 }, function(data) {
                if (data.error_code == 0) {
                    _self.classify1 = data.data;

                } else {
                    alert(data.msg);
                }
            });
            // 获取个人标签
            var defaults2 = {
                tagType: 2,
                type: _self.typeID
            };
            var data2 = $.extend(defaults2, {});
            Common.ajaxCall({ url: "look_getTagList", datatype: 'json', type: 'post', data: data2 }, function(data) {
                if (data.error_code == 0) {
                    _self.classify2 = data.data;

                } else {
                    alert(data.msg);
                }
            });

        },
        side: function() { //关闭筛选
            this.screenSide = false;
        },
        loadPhoto: function() {
            // 比例
            myJS.imgScale('.j_4', '4', '3');
            myJS.imgScale('.j_10', '10', '13');
            myJS.ImgCenter('.loadImg', 'images/NotPreview.jpg');
        },
        slides: function(index, e) {
            var _self = this;
            _self.tabs = index;

            if (e && typeof(e) != 'undefined') {
                $(e.currentTarget).addClass('on').siblings().removeClass('on');
            }

            _self.newList = {
                isLoading: true,
                pageSize: PAGESIZE,
                pageIndex: 1
            };
            _self.reqOut = false;
            _self.data = []; //清空上一次请求vm储存的数据
            if (e && typeof(e) != 'undefined') {
                if (index === 3) {
                    if ($(e.currentTarget).hasClass('upward')) { //评分倒序
                        $(e.currentTarget).addClass('down').removeClass('upward');
                        _self.tabs = 4;
                    } else {
                        $(e.currentTarget).removeClass('down').addClass('upward');
                    }
                } else { //评分正序
                    $('.up').removeClass('upward').removeClass('down');
                }
            }
            if (_self.tabs <= 4) {
                $.setCookie('meetingtabs', _self.tabs); //保存最近的Tab
            }
            _self.loadlist(_self.tabs);
        },
        layWay: function() { //控制显示方式
            var _self = this;
            if (!_self.layout) {
                //TODO:切换展示方式是否让列表激活？
                //_self.newList.isLoading = true;
                //_self.reqOut = false;
                _self.layout = true;
                $('.cateIcon').removeClass('on');
            } else {

                //_self.newList.isLoading = true;
                //_self.reqOut = false;
                _self.layout = false;
                $('.cateIcon').addClass('on');
            }
            _self.loadPhoto();
        },
        filterSec: function(e) { //选择筛选标签
            var _self = this;

            var $cateList = $(e.currentTarget).parents('.cateList');
            if ($(e.currentTarget).hasClass('on')) {
                $(e.currentTarget).removeClass('on');
            } else {
                $cateList.find('li').removeClass('on');
                $(e.currentTarget).addClass('on');
            }

        },
        filterReg: function() { //确认筛选标签
            var _self = this;
            var classifyDom = $('.j_classify li');
            var arrDom = $('.j_tagList li');
            var tagTypes = [];
            //选中的分类
            [].forEach.call(classifyDom, function(value, index, context) {
                if ($(value).hasClass('on')) {
                    _self.typeID = $(value).data('id');
                    _self.typeName = $(value).data('name');
                }
                //console.log(tagTypes);
            });
            //遍历选中标签
            [].forEach.call(arrDom, function(value, index, context) {
                if ($(value).hasClass('on')) {
                    tagTypes.push($(value).data('name'));
                }
                //console.log(tagTypes);
            });
            //if(tagTypes.length>0){   //有选择标签才进行请求
            _self.newList = {
                isLoading: true,
                pageSize: PAGESIZE,
                pageIndex: 1
            };
            _self.data = [];

            _self.tagTypes = tagTypes.join(',');
            _self.loadlist(_self.tabs);
            //$('.meetUl li').eq(0).addClass('on').siblings().removeClass('on').removeClass('upward').removeClass('down');
            _self.screenSide = false;
            // }else{
            // 	_self.screenSide = false;
            // 	//alert('您还没有选择！');
            // }

        },
        reset: function() { //重置筛选标签
            var arrDom = $('.cateList li');
            //var tagTypes = '';
            [].forEach.call(arrDom, function(value, index, context) {
                if ($(value).hasClass('on')) {
                    $(value).removeClass('on');
                }
            });
        },
        swipeLeft: function(e) {
            var shareColl = $(e.target).parents('li');
            var drift = ($(e.target).parents('li').width()) / 3;
            //回复原位置
            // $(e.target).parents('ul').children().animate({left:0});
            //   $(e.target).parents('ul').children().find('.shareColl').animate({width:0,right:0});

            console.log(e.deltaX);
            if (e.deltaX < 0) { //左滑
                if (e.deltaX < -drift) {
                    $(e.target).parents('li').animate({ left: -drift });
                    var height = $(e.target).parents('li').outerHeight();
                    shareColl.find('.shareColl').animate({ width: drift, right: -drift }).show().css('line-height', height + 'px');
                }
            } else { //右滑
                if (e.deltaX > drift) {
                    $(e.target).parents('li').animate({ left: 0 }).find('.shareColl').fadeOut('fast');
                }
            }
        },
        share: function(obj, e) {
            $(e.target).parents('ul').children().animate({ left: 0 }).find('.shareColl').fadeOut('fast'); //将左滑的元素复位
            var _self = this;
            _self.showModal = true;
            console.log(obj);
            _self.shareObj = {
                dataID: obj.shareId, //文档id
                shareTit: obj.shareTit, //文档标题
                sharePic: obj.sharePic,    //文档图片
                isdoc : obj.isdoc   //是不是文档
            };

        },
        shareReg: function(userList) {
            var _self = this;
            if (!userList) { //如果没选择分享对象回到原来界面
                _self.showModal = false;
                return;
            }

            alert({
                close: false,
                text: '分享',
                description: '<div class="clearfix shareTxt"><span class="j_1 photo"><img class="s_34" src="'+Common.wordIcon(_self.shareObj.sharePic,_self.shareObj.isdoc) +'" onerror=\"javascript:this.src=\'images/icon/type/OTHER.png\';this.onerror=null;\"></span><span class="text">' + _self.shareObj.shareTit + '</span></div>',
                fillInput: true,
                kind: 2,
                okEvent: function() {
                    var data = {
                        dataID: _self.shareObj.dataID,
                        userList: userList,
                        comment: _self.inputText,
                        type: 1
                    };
                    data = Common.jsonEncode(data);
                    Common.ajaxCall({ url: 'look_share', datatype: 'json', type: 'get', data: data }, function(data) {
                        if (data.error_code == 0) {
                            var obj = data.data[0];
                            var code = obj.code;
                            var pic = code == 1 ? "moneyPig.png" : "lebel.png";
                            alert({
                                text: '<img src="images/' + pic + '"/>',
                                description: obj.str,
                                kind: 0
                            });
                        } else {
                            alert(data.msg);
                        }
                    });
                }
            });
        },
        //收藏
        Collection: function(obj, e) {
            var _self = this;
            _self.addShow = false;
            $(e.target).parents('li').animate({ left: 0 }).find('.shareColl').fadeOut(); //将左滑的元素复位
            var data = {
                dataID: obj.dataID,
                type: 1,
                isCollection: 1
            };
            data = Common.jsonEncode(data);
            Common.ajaxCall({ url: 'look_addCollection', datatype: 'json', type: 'get', data: data }, function(data) {
                if (data.error_code == 0) {
                    var obj = data.data[0];
                    var code = obj.code;
                    var pic = code == 1 ? "moneyPig.png" : "lebel.png";
                    alert({
                        text: '<img src="images/' + pic + '"/>',
                        description: obj.str,
                        kind: 0
                    });
                } else {
                    alert(data.msg);
                }
            });
        },
        back: function() {
            window.location.href = decodeURIComponent(backUrl);
        },
        toartDetail: function(id) {
            $.setCookie('layout', this.layout ? "true" : "false"); //保存最近的layout
            window.location.href = "articleDetail.html?id=" + id + "&back=" + forword;
        },
        changeTag: function(id, name) {
            var _self = this;
            if (history.pushState && name) {
                _self.typeName = name;
                history.pushState({ title: name }, name, "meeting.html?id=" + id + "&name=" + name);
            }
        },
        //由类型显示缩略图
        showThumbnail: function(pic, suffix) {
            //音频文件
            if (typeof(suffix) != 'undefined') {
                suffix = suffix.toLowerCase();
                if (suffix == "mp3" || suffix == "wma" || suffix == "wav") {
                    return "images/AudioFile.jpg";
                }
                //
                if (suffix == "html" || suffix == "zip" || suffix == "rar") {
                    return "images/preview.jpg";
                }
                //不支持预览
                if (suffix == "ai" ||
                    suffix == "prt" ||
                    suffix == "sch" ||
                    suffix == "pcb" ||
                    suffix == "sldasm" ||
                    suffix == "sldprt" ||
                    suffix == "svg" ||
                    suffix == "catpart") {
                    return "images/NotPreview.jpg";
                }
            }
            if (typeof(pic) == 'undefined') {
                return "images/preview.jpg";
            }
            //返回原来的
            return pic;
        }
    },
    watch: {
        "data": function() {
            this.loadPhoto();
        },
        "layout": function() {
            this.loadPhoto();
        },
        "classify1": function() {
            var _self = this;
            var arrDom = $('.cateList li');
            var tagTypesArr = _self.tagTypes.split(',');
            [].forEach.call(arrDom, function(value, index, context) {
                if (_self.tagTypes.indexOf($(value).data('name')) > -1) {
                    console.log($(value).find('a').html());
                    $(value).addClass('on');
                }
            });
        },
        "classify2": function() {
            var _self = this;
            var arrDom = $('.cateList li');
            var tagTypesArr = _self.tagTypes.split(',');
            [].forEach.call(arrDom, function(value, index, context) {
                if (tagTypesArr.indexOf($(value).data('name')) > -1) {
                    console.log($(value).find('a').html());
                    $(value).addClass('on');
                }
            });
        }
    }
});